//
//  MCNoVideoTrainVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/21.
//

import UIKit
import SnapKit
import JKSwiftExtension
import Toast_Swift
import MMPopupView
import QMUIKit
import MBCircularProgressBar
import ZFPlayer

class MCNoVideoTrainVc: MCBaseVc, UIViewControllerTransitioningDelegate {
    
    
    public var planId:String = ""
    
    public var userPlanId:String = ""
    
    public var detailInfoList:Array<MCStartXunLianActionPlanDetailList?> = [MCStartXunLianActionPlanDetailList?]()
    
    
    private var playerController:ZFPlayerController!
    
    private var controlView:MCControllerView!
    
    private var controllerImageView:UIImageView!

    private var playNanager:ZFAVPlayerManager!
    
    @IBOutlet weak var actionPlayTableView: UITableView!
    
    private let actionNoVideoTrainIdentifier = "actionNoVideoTrainIdentifier"
    
    private var  startXunLianAllModel:MCStartXunLianAllModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let showDigalInfoVc = MCShowDigatalInfoVc.init()
        showDigalInfoVc.modalPresentationStyle = .custom
        showDigalInfoVc.modalTransitionStyle = .crossDissolve
        showDigalInfoVc.transitioningDelegate = self
        self.present(showDigalInfoVc, animated: false) {
            
        }
        
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        self.navigationItem.title = ""
        getHaveVideoTrainData()
        
        playNanager = ZFAVPlayerManager.init()
        
        
        self.controlView = MCControllerView.init()
        
    
        playerController = ZFPlayerController(scrollView: self.actionPlayTableView, playerManager: self.playNanager, containerViewTag: 100)
   
        self.playerController.controlView = self.controlView
        
        self.playerController.pauseWhenAppResignActive = false
        self.playerController.isWWANAutoPlay = true
        self.playerController.allowOrentitaionRotation = false
        self.playerController.playerDisapperaPercent = 1.0
        self.playerController.disableGestureTypes = [.pan,.pinch]
        
        
        //播放完成
        self.playerController.playerDidToEnd = { asset in
            self.playerController.currentPlayerManager.replay()
            
        }
        
        self.playerController.zf_scrollViewDidEndScrollingCallback = { (_ indexPath:IndexPath) in
            if (self.playerController.playingIndexPath != nil) {
                return
            }
            self.playTheVideoAtIndexPath(indexPath: indexPath)
            
        }
        
        self.actionPlayTableView.dataSource = self
        self.actionPlayTableView.delegate = self
        self.actionPlayTableView.isPagingEnabled = true
        self.actionPlayTableView.isUserInteractionEnabled = false
        self.actionPlayTableView.register(UINib(nibName: "MCNoVideoTrainTableCell", bundle: Bundle.main), forCellReuseIdentifier: actionNoVideoTrainIdentifier)
       
        
        
        
        
        
    }
    
    //获取音频-(暂时无法使用)
    func getMusicData() -> Void{
        NetWorkRequest(HaveVideoTrainVM.getmusicListStartOrEnd) { ResponseModel in
            
            
            
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    //列表数据
    func getHaveVideoTrainData() -> Void {
        
        NetWorkRequest(HaveVideoTrainVM.startVideoTask(planId:userPlanId, userPlanId:planId)) { ResponseModel in
            
            let startXunLianAllModel = MCStartXunLianAllModel.init(JSONString: ResponseModel.dataString)
            
            self.startXunLianAllModel = startXunLianAllModel
            
            self.detailInfoList.append(contentsOf: startXunLianAllModel?.actionPlanDetailList ?? [])
            
            self.actionPlayTableView.reloadData()
            
            self.actionPlayTableView.scrollToRow(at:IndexPath.SubSequence(row: 0, section: 0), at: .none, animated: true)
             
            
            self.playerController.zf_filterShouldPlayCellWhileScrolled { (_ indexpath:IndexPath) in
                self.playTheVideoAtIndexPath(indexPath: indexpath)
            }
             
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    //列表
    @IBAction func allBtnListSender(_ sender: UIButton) {
        let trainListView = MCTrainListViewVc.init()
        trainListView.detailInfoList = self.detailInfoList
        trainListView.transitioningDelegate = self
        self.present(trainListView, animated: true) {
            
        }
    }
    
    
    //播放或暂停
    @IBAction func playOrPauseSender(_ sender: UIButton) {
        
        
    
    }
    
    
    //播放开始
    @IBAction func startSender(_ sender: UIButton) {
        
        
        
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScroll()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
    
    
    func playTheVideoAtIndexPath(indexPath:IndexPath) -> Void {
        
        let trainInfoList = self.detailInfoList[indexPath.section]
        
        let trainActionList = trainInfoList?.actionPlanDetailActionList?[indexPath.row]
        
        self.playerController.playTheIndexPath(indexPath as IndexPath, assetURL: URL(string:trainActionList?.actionVideoUrl ?? "")!)
         
    }
    
    
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return  CustomPresentationVc.init(presentedViewController: presented, presenting: presenting)
    }
    
}

extension MCNoVideoTrainVc:UITableViewDelegate,UITableViewDataSource  {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.detailInfoList.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let infoActionList = self.detailInfoList[section]?.actionPlanDetailActionList
        
        return infoActionList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScreenHeight - 130
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCNoVideoTrainTableCell = tableView.dequeueReusableCell(withIdentifier: actionNoVideoTrainIdentifier, for: indexPath) as! MCNoVideoTrainTableCell
        
        let trainInfoList = self.detailInfoList[indexPath.section]
        
        let trainActionList = trainInfoList?.actionPlanDetailActionList?[indexPath.row]
        
        cell.currentActionLabel.text = trainActionList?.actionName
        
        cell.currentHeaderZuActionLabel.text = "\(indexPath.section + 1)组 \(String(describing:(trainActionList?.actionTime)!))s"
        
        cell.timeAndProgressLabel.text = "用时 \((self.startXunLianAllModel?.planNeedTime ?? 0) / 60):\((self.startXunLianAllModel?.planNeedTime ?? 0) % 60)"
        
        cell.indexPath = indexPath
        
        cell.timeBreakTime = trainActionList?.actionTime ?? 0
        
        
        cell.nextPath = { indexValue  in
            self.actionPlayTableView.scrollToRow(at:indexValue, at: .none, animated: true)
            self.actionPlayTableView.selectRow(at: indexValue, animated: true, scrollPosition: .none)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let trainInfoList = self.detailInfoList[indexPath.section]
        
        let trainActionList = trainInfoList?.actionPlanDetailActionList?[indexPath.row]
         
        let cell:MCNoVideoTrainTableCell = tableView.cellForRow(at: indexPath) as! MCNoVideoTrainTableCell
        
        cell.timeBreakTime = trainActionList?.actionTime ?? 0
        
        self.playTheVideoAtIndexPath(indexPath: indexPath)
        
    }
    
    
}
